/*
 * @Author: halande
 * @Date: 2021-04-15 17:48:51
 * @LastEditTime: 2021-05-12 16:12:34
 * @LastEditors: Please set LastEditors
 * @Description: 图文导航滑动相关的函数集合
 * @FilePath: /lego-nuxt/components/modules/NavigateModule/navigateModule.extends.js
 */

const NavigateModuleExtends = {
  methods: {
    debounce: function (fn, wait) {
      let timer = null
      return function () {
        if (timer !== null) {
          clearTimeout(timer)
        }
        timer = setTimeout(fn, wait)
      }
    },
    scrollNavigate (x) {
      let node = document.getElementById(this.componentId + '_section')
      let fn = this.debounce(function () {
        node.scrollTo({
          left: x,
          behavior: 'smooth',
        })
      }, 100)

      fn()
    },
    scrollNavigateTo (x) {
      let node = document.getElementById(this.componentId + '_section')
      let timer = null

      if (timer) {
        clearInterval(timer)
      }
      let target = 0
      timer = setInterval(function () {
        // 随定时器达到匀速
        // 15
        target = node.scrollLeft + 150
        node.scrollTo(target, 0)
        // 20
        if (x - target < 1) {
          node.scrollTo(x, 0)
          clearInterval(timer)
        }
      }, 1)
    },
    scrollToFirst (x) {
      let node = document.getElementById(this.componentId + '_section')
      let timer = null

      if (timer) {
        clearInterval(timer)
      }
      let target = 0
      // 10
      timer = setInterval(function () {
        // 随定时器达到匀速
        target = node.scrollLeft - 150
        node.scrollTo(target, 0)
        if (target - x < 1) {
          node.scrollTo(x, 0)
          clearInterval(timer)
        }
      }, 1)
    },
    onLeftScroll () {
      if (this.indicatorIndex === 1) {
        let w = document.getElementById(this.componentId + '_section')
          .clientWidth

        this.scrollNavigateTo(w)
        this.indicatorIndex = 2
      }
    },
    onRightScroll () {
      if (this.indicatorIndex === 2) {
        this.indicatorIndex = 1
        this.scrollToFirst(0)
      }
    },
    onOtherScroll () {
      let node = document.getElementById(this.componentId + '_section')
      let left = node.scrollLeft

      let w = node.clientWidth

      if (left > w / 2) {
        this.indicatorIndex = 2
        this.scrollNavigate(w)
      } else {
        this.indicatorIndex = 1
        this.scrollNavigate(0)
      }
    }
  }
}

export default NavigateModuleExtends
